package br.com.srv.componentes.rota.dao;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import br.com.srv.commons.dao.hibernate.BasicDAOImpl;
import br.com.srv.model.RotaTO;

public class RotaDAOImpl extends BasicDAOImpl implements RotaDAO{

	public List<RotaTO> buscarRotas(RotaTO rotaTO) throws Exception {
		int count = 0;
		String query = "SELECT rota FROM RotaTO rota ";

		if (rotaTO.getDescricao() != null && !rotaTO.getDescricao().equals("")) {
			query = montarQuery(query, count);
			query += "rota.descricao like '" + rotaTO.getDescricao() + "%'";
			count++;
		}
		
		if (rotaTO.getCodigo() != null && !rotaTO.getCodigo().equals("")) {
			query = montarQuery(query, count);
			query += "rota.codigo like '" + rotaTO.getCodigo() + "%'";
			count++;
		}	
		
		if (rotaTO.getNome() != null && !rotaTO.getNome().equals("")) {
			query = montarQuery(query, count);
			query += "rota.nome like '" + rotaTO.getNome() + "%'";
			count++;
		}	
		
		if (rotaTO.getClienteId() != null && !rotaTO.getClienteId().equals("")) {
			query = montarQuery(query, count);
			query += "rota.clienteId = '" + rotaTO.getClienteId().toString() + "'";
			count++;
		}
		
		if (rotaTO.getStatus() != null && !rotaTO.getStatus().equals("")) {
			query = montarQuery(query, count);
			query += "rota.status = " + rotaTO.getStatus() + "";
			count++;
		}
		
		query += " order by rota.codigo";
		
		return findByQuery(query);
	}
	
	public Integer getUlitimaHoraContratadaPorPonto(Integer idPonto) {
		String queryStr = "select max(hc.codigo) from " +
				"HoraContratadaTO hc where hc.pontoFisTO.id = ?";
		
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		Query query = session.createQuery(queryStr);
		query.setInteger(0, idPonto);
		Iterator rs = query.iterate();
		
		while (rs.hasNext()) {
			Integer id = (Integer) rs.next();
			return id;
		}
		
		return 0;
	}

}
